package com.stationbuilding.fragment.home;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;


import com.bumptech.glide.Glide;
import com.stationbuilding.MyApplication;
import com.stationbuilding.R;
import com.stationbuilding.TestData;
import com.stationbuilding.activity.MainActivity;
import com.stationbuilding.adapter.home.HomeListAdapter;
import com.stationbuilding.adapter.quality.QualityFragmentHomeListAdapter;
import com.stationbuilding.api.RetrofitManager;
import com.stationbuilding.bean.FileBean;
import com.stationbuilding.bean.ProjectInfoBean;
import com.stationbuilding.bean.QuestionBean;
import com.stationbuilding.bean.QuestionListBean;
import com.stationbuilding.bean.QuestionTypeBean;
import com.stationbuilding.constants.Constants;
import com.stationbuilding.utils.DateUtils;
import com.stationbuilding.utils.DialogUtils;
import com.stationbuilding.utils.PreferenceHelper;
import com.stationbuilding.view.ListViewForScrollView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class HomeFragment extends Fragment {

    private View view;
    private Dialog dialog;
    private HomeListAdapter homeListAdapter;
    private List<QuestionTypeBean> questionTypeList = new ArrayList<>();
    private String token = PreferenceHelper.getInstance(getActivity()).getToken();
    private TextView safeTv;
    private TextView qualityTv;
    private TextView progressTv;
    private TextView startDate;
    private TextView endDate;
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.safe:
                case R.id.safe_img:
                    Toast.makeText(getActivity(), "安全", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.quality:
                case R.id.quality_img:
                    Toast.makeText(getActivity(), "质量", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.progress:
                case R.id.progress_img:
                    Toast.makeText(getActivity(), "进度", Toast.LENGTH_SHORT).show();
                    break;
                case R.id.safe_tv:
                case R.id.quality_tv:
                case R.id.progress_tv:
                    changeData(v.getId());
                    break;
                case R.id.start_date:
                case R.id.start_date_img:
                case R.id.end_date:
                case R.id.end_date_img:
                    selectDate(v.getId());
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false);
        initProjectInfo();
        initImageView();
        initEvent();
        initListView();
        return view;
    }

    /**
     * 初始化站房信息
     */
    private void initProjectInfo() {
        // 获取站房ID
        String projectId = PreferenceHelper.getInstance(getActivity()).getProjectId();
        // 获取用户ID
        String userId = PreferenceHelper.getInstance(getActivity()).getUserId();
        RetrofitManager.toSubscribe(RetrofitManager.getApiService().getProjectInfoById(token, projectId, userId), new Observer<ProjectInfoBean>() {
            @Override
            public void onComplete() {
                DialogUtils.closeDialog(dialog);
            }
            @Override
            public void onError(Throwable e) {
                Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                DialogUtils.closeDialog(dialog);
            }
            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
//                dialog = DialogUtils.createLoadingDialog(getActivity(), "数据加载中...");
            }
            @Override
            public void onNext(ProjectInfoBean projectInfoBean) {
                if (projectInfoBean.getCode() != 0) {
                    Toast.makeText(getActivity(), "获取站房信息失败:" + projectInfoBean.getCode(), Toast.LENGTH_SHORT).show();
                } else {
                    PreferenceHelper.getInstance(getActivity()).saveProjectId(projectInfoBean.getProjectInfoEntity().getId());
                    TextView projectName = (TextView) view.findViewById(R.id.project_name);
                    TextView projectDept = (TextView) view.findViewById(R.id.project_dept);
                    TextView projectStartDate = (TextView) view.findViewById(R.id.project_start_date);
                    TextView projectEndDate = (TextView) view.findViewById(R.id.project_end_date);
                    projectName.setText(projectInfoBean.getProjectInfoEntity().getProjectName());
                    projectDept.setText(projectInfoBean.getProjectInfoEntity().getDeptName());
                    projectStartDate.setText(projectInfoBean.getProjectInfoEntity().getStartDateStr());
                    projectEndDate.setText(projectInfoBean.getProjectInfoEntity().getEndDateStr());
                    initBanner(projectInfoBean.getProjectInfoEntity().getDocPath());
                }
            }
        });
    }

    /**
     * 初始化轮播图
     */
    private void initBanner(List<String> docPathList) {
        Banner banner = (Banner) view.findViewById(R.id.project_photo);
        //设置内置样式。
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new ProjectPhotoLoader());
        //设置图片网址或地址的集合
        for (int i = 0; i < docPathList.size(); i++) {
            docPathList.set(i, Constants.BASE_URL + docPathList.get(i).replaceAll("\\\\", "/"));
        }
        banner.setImages(docPathList);
        //设置轮播的动画效果
        banner.setBannerAnimation(Transformer.Default);
        //设置轮播间隔时间
        banner.setDelayTime(3000);
        //设置是否为自动轮播，默认是“是”。
        banner.isAutoPlay(true);
        //设置指示器的位置，小点点，左中右。
        banner.setIndicatorGravity(BannerConfig.CENTER);
        //必须最后调用的方法，启动轮播图。
        banner.start();
    }

    /**
     * 初始化安全/质量/进度图片按钮
     */
    private void initImageView() {
        ImageView safeImg = (ImageView) view.findViewById(R.id.safe_img);
        ImageView qualityImg = (ImageView) view.findViewById(R.id.quality_img);
        ImageView progressImg = (ImageView) view.findViewById(R.id.progress_img);
        TextView safe = (TextView) view.findViewById(R.id.safe);
        TextView quality = (TextView) view.findViewById(R.id.quality);
        TextView progress = (TextView) view.findViewById(R.id.progress);
        safe.setOnClickListener(onClickListener);
        quality.setOnClickListener(onClickListener);
        progress.setOnClickListener(onClickListener);
        safeImg.setOnClickListener(onClickListener);
        qualityImg.setOnClickListener(onClickListener);
        progressImg.setOnClickListener(onClickListener);
    }

    /**
     * 初始化事件
     */
    private void initEvent() {
        // 安全质量进度切换
        safeTv = (TextView) view.findViewById(R.id.safe_tv);
        qualityTv = (TextView) view.findViewById(R.id.quality_tv);
        progressTv = (TextView) view.findViewById(R.id.progress_tv);
        safeTv.setOnClickListener(onClickListener);
        qualityTv.setOnClickListener(onClickListener);
        progressTv.setOnClickListener(onClickListener);
        // 获取系统时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        // 结束日期
        endDate = (TextView) view.findViewById(R.id.end_date);
        endDate.setText(DateUtils.formatDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)));
        // 开始日期
        calendar.add(Calendar.MONTH, -1);
        startDate = (TextView) view.findViewById(R.id.start_date);
        startDate.setText(DateUtils.formatDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)));
        ImageView startDateImg = (ImageView) view.findViewById(R.id.start_date_img);
        ImageView endDateImg = (ImageView) view.findViewById(R.id.end_date_img);
        startDate.setOnClickListener(onClickListener);
        startDateImg.setOnClickListener(onClickListener);
        endDate.setOnClickListener(onClickListener);
        endDateImg.setOnClickListener(onClickListener);
    }

    /**
     * 初始化统计列表
     */
    private void initListView() {
        ListViewForScrollView homeListView = (ListViewForScrollView) view.findViewById(R.id.home_list);
        homeListView.setFocusable(false);
        homeListAdapter = new HomeListAdapter(questionTypeList);
        homeListView.setAdapter(homeListAdapter);
        loadData();
    }

    /**
     * 数据加载
     */
    private void loadData() {
        questionTypeList = TestData.getSafeData();
        homeListAdapter.setList(questionTypeList);
        homeListAdapter.notifyDataSetChanged();
//        RetrofitManager.toSubscribe(
//                RetrofitManager.getApiService().getQuestionListByStatus(token, expandId, Constants.QUESTION_TYPE_QUALITY, initiator),
//                new Observer<QuestionListBean>() {
//
//                    @Override
//                    public void onComplete() {
//                        DialogUtils.closeDialog(dialog);
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
//                        DialogUtils.closeDialog(dialog);
//                    }
//
//                    @Override
//                    public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
//                        dialog = DialogUtils.createLoadingDialog(getActivity(), "数据加载中...");
//                    }
//
//                    @Override
//                    public void onNext(QuestionListBean questionListBean) {
//                        questionList = questionListBean.getQuestionList();
//                        homeListAdapter.setList(questionList);
//                        homeListAdapter.notifyDataSetChanged();
//                    }
//                });
    }

    /**
     * 数据变换
     */
    private void changeData(int id) {
        if (R.id.safe_tv == id) {
            safeTv.setTextColor(ContextCompat.getColor(getActivity(), R.color.dodgerblue_selected));
            qualityTv.setTextColor(ContextCompat.getColor(getActivity(), R.color.gray_8f));
            progressTv.setTextColor(ContextCompat.getColor(getActivity(), R.color.gray_8f));
            questionTypeList = TestData.getSafeData();
        } else if (R.id.quality_tv == id) {
            safeTv.setTextColor(ContextCompat.getColor(getActivity(), R.color.gray_8f));
            qualityTv.setTextColor(ContextCompat.getColor(getActivity(), R.color.dodgerblue_selected));
            progressTv.setTextColor(ContextCompat.getColor(getActivity(), R.color.gray_8f));
            questionTypeList = TestData.getQualityData();
        } else {
            safeTv.setTextColor(ContextCompat.getColor(getActivity(), R.color.gray_8f));
            qualityTv.setTextColor(ContextCompat.getColor(getActivity(), R.color.gray_8f));
            progressTv.setTextColor(ContextCompat.getColor(getActivity(), R.color.dodgerblue_selected));
            questionTypeList = TestData.getProgressData();
        }
        homeListAdapter.setList(questionTypeList);
        homeListAdapter.notifyDataSetChanged();
//        RetrofitManager.toSubscribe(
//                RetrofitManager.getApiService().getQuestionListByStatus(token, expandId, Constants.QUESTION_TYPE_QUALITY, initiator),
//                new Observer<QuestionListBean>() {
//
//                    @Override
//                    public void onComplete() {
//                        DialogUtils.closeDialog(dialog);
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
//                        DialogUtils.closeDialog(dialog);
//                    }
//
//                    @Override
//                    public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
//                        dialog = DialogUtils.createLoadingDialog(getActivity(), "数据加载中...");
//                    }
//
//                    @Override
//                    public void onNext(QuestionListBean questionListBean) {
//                        questionList = questionListBean.getQuestionList();
//                        homeListAdapter.setList(questionList);
//                        homeListAdapter.notifyDataSetChanged();
//                    }
//                });
    }

    private void selectDate(int id) {
        DatePickerDialog datePickerDialog;
        final Calendar ca = Calendar.getInstance();
        int year = ca.get(Calendar.YEAR);
        int month = ca.get(Calendar.MONTH);
        int day = ca.get(Calendar.DAY_OF_MONTH);
        if (R.id.start_date == id || R.id.start_date_img == id) {
            datePickerDialog = new DatePickerDialog(getActivity(), R.style.DatePickerDialogTheme, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                    startDate.setText(DateUtils.formatDate(year, month, dayOfMonth));
                }
            }, year, month, day);
            if (!TextUtils.isEmpty(endDate.getText())) {
                DatePicker datePicker = datePickerDialog.getDatePicker();
                datePicker.setMaxDate(DateUtils.strToDate(endDate.getText().toString()).getTime());
            }
        } else {
            datePickerDialog = new DatePickerDialog(getActivity(), R.style.DatePickerDialogTheme, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                    endDate.setText(DateUtils.formatDate(year, month, dayOfMonth));
                }
            }, year, month, day);
            if (!TextUtils.isEmpty(startDate.getText())) {
                DatePicker datePicker = datePickerDialog.getDatePicker();
                datePicker.setMinDate(DateUtils.strToDate(startDate.getText().toString()).getTime());
            }
        }
        datePickerDialog.show();
    }

    private class ProjectPhotoLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            Glide.with(context).load((String) path).into(imageView);
        }
    }
}
